<template>
  <div style="height: 700px">
    <unfold class="reason">
      <!-- 左侧内容 -->
      <template v-slot:tree-list>
        <div class="left box tree-list">
          <!-- header -->
          <div class="tree-head bg-primary text-white text-weight-regular box-header flex items-center justify-between">
            <div>
              <div class="head-title inline-block user-select-none">驱动列表</div>
            </div>
            <div>
              <div class="fr font-size-16 margin-l-10">
                <q-btn flat dense color="white" icon="iconfont icontubiao-16" class="font-size-16 icon-btn"
                       :disable="isPreVersion || !selectedTypeId" @click="delType">
                  <q-tooltip>删除</q-tooltip>
                </q-btn>
              </div>
              <div class="fr font-size-16 margin-l-10">
                <q-btn flat dense color="white" icon="iconfont icontubiao-39" class="font-size-16 icon-btn"
                       @click="addType" :disable="disableAdd">
                  <q-tooltip>新增</q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>
          <q-scroll-area class="box-content bg-white full-height" :thumb-style="thumbStyle">
            <q-list style="min-width: 100px;">
              <div v-for="item in typeList" :key="item.id">
                <q-item
                  class="role-item"
                  :active="selectedTypeId === item.id"
                  active-class="activated"
                  @click="onTypeClick(item)"
                  clickable
                  v-ripple
                >
                  <q-item-section>
                    <div class="flex full-width no-wrap items-center">
<!--                      <div class="status"></div>-->
                      <div class="full-width text-ellipsis">{{ item.driverName }}
                        <q-tooltip>{{ item.driverName }}</q-tooltip>
                      </div>
                    </div>
                  </q-item-section>
                </q-item>
                <q-separator/>
              </div>
            </q-list>
          </q-scroll-area>
        </div>
      </template>
      <!-- 左侧内容End -->
      <!-- 右侧内容 -->
      <template v-slot:content>
        <div class="right box page-content flex column scrollbar">
          <div class="relative" v-show="selectedTypeId">
            <div class="flex column">
              <q-tabs
                v-model="tab"
                shrink stretch dense
                inline-label
                align="left"
                active-color="primary"
                indicator-color="primary"
              >
                <q-tab name="driver" label="驱动&子设备信息"/>
                <q-tab v-if="!isCnc" name="point" label="点位"/>
              </q-tabs>
              <q-tab-panels v-model="tab" animated style="height: calc(100% - 67px)" class="scrollbar">
                <q-tab-panel name="driver" style="padding:0" class="full-height">
                  <div class="flex">
                    <div class="driver-box" style="margin-right: 0">
                      <div class="title">驱动信息</div>
                      <div class="content-wrapper">
                        <div class="flex items-center padding-b-20" v-if="isCnc">
                          <div>关联设备:{{ driverDevice }}</div>
                          <q-icon v-if="driverDeviceObj && driverDeviceObj.id" name="iconfont icontubiao-58" class="icon margin-l-5 cursor-pointer" @click="toDetail">
                            <q-tooltip>跳转到实时数据</q-tooltip>
                          </q-icon>
                        </div>
                        <div class="row padding-b-20">
                          <div class="col">控制器类型:{{ driverDetail[0] }}</div>
                          <div class="col">控制器品牌:{{ driverDetail[1] }}</div>
                        </div>
                        <div class="row padding-b-20">
                          <div class="col">控制器型号:{{driverDetail[2]}}</div>
                          <div class="col">协议名称:{{ driverDetail[3]}}</div>
                        </div>
                        <div class="row padding-b-20">
                          <div class="col">IOT接口:{{driverDetail[4]}}</div>
                          <div class="col">驱动版本号: {{currentDriverInfo.driverVersion}}</div>
                        </div>
                        <div class="padding-b-20">
                          <div>驱动描述: {{ driverDescription }}</div>
                        </div>
                        <div v-if="isCnc">
                          <div>清零/累加: {{ driverDeviceObj.partcountName }}</div>
                        </div>
                      </div>
                    </div>
                    <div class="driver-box" style="flex: 2;margin-right: 5px">
                      <div class="title">子设备信息</div>
                      <div class="content-wrapper scrollbar">
                        <SubDriverInfoDetail :driverInfo="driverInfo" :controller-type="currentDriverInfo.type + ''" />
                      </div>
                    </div>
                  </div>
                </q-tab-panel>
                <q-tab-panel name="point" style="padding:0" class="full-height">
                  <div class="margin-t-10">
                    <PointTable ref="pointTable" :is-detail="true" height="500px" :controller-type="controllerType" :box-driver-id="currentDriverInfo.id" :isPreVersion="isPreVersion" :driverParams="driverParams"/>
                  </div>
                </q-tab-panel>
              </q-tab-panels>
            </div>
            <div class="btn-pos">
              <q-btn
                label="网络诊断"
                color="primary"
                class="btn margin-r-10"
                outline
                @click="networkAsset"/>
              <q-btn
                label="配置"
                color="primary"
                class="btn"
                unelevated
                @click="driverSetting"/>
            </div>=
          </div>
        </div>
      </template>
      <!-- 右侧内容End -->
    </unfold>

    <!-- 控制器类型 -->
    <ControllerDialog ref="controllerDialog" @changeType="changeType" :typeList="typeList" :controller-type="controllerTypes"/>

    <!-- 驱动配置 -->
    <DriverDialog ref="driverDialog"
                  :controllerType="controllerType"
                  :driverParams="driverParams"
                  @successSubmit="successDriver"
                  :driverDeviceObj="driverDeviceObj"
                  :isPreVersion="isPreVersion"
                  :productsCnc="productsCnc"
                  :updateVersion="updateVersion"
                  :boxRemark="boxRemark"
                  :driverListAll="driverListFilter"/>

    <!-- 子设备配置 -->
    <SubDeviceDialog  ref="subDeviceDialog"
                      :controllerType="controllerType"
                      :driverConfigData="driverConfigData"
                      :currentDriverInfo="currentDriverInfo"
                      :is-compete="dialogType===2"
                      :isPreVersion="isPreVersion"
                      @successSubmit="successSubDevice"
                      :updateVersion="updateVersion"
                      :driverParams="driverParams"/>

    <!-- 点位配置 -->
    <PointDialog ref="pointDialog"
                 :driverConfigData="driverConfigData"
                 :driverParams="driverParams"
                 :currentDriverInfo="currentDriverInfo"
                 :detailInfo="detailInfo"
                 :updateVersion="updateVersion"
                 :isPreVersion="isPreVersion"
                 @successSubmit="successPoint"
                 :controllerType="currentDriverInfo.type + ''"
    />

    <NetworkDialog ref="networkDialog" :ucloudBoxId="driverParams.ucloudBoxNum"/>
  </div>
</template>

<script>
import Unfold from '../../../../components/unfold/index.vue'
import ControllerDialog from '../list-components/gateway-dialog/controller-dialog.vue'
import DriverDialog from '../../components/list-components/step-dialog/driver-dialog.vue'
import PointDialog from '../../components/list-components/step-dialog/point-dialog.vue'
import SubDeviceDialog from '../../components/list-components/step-dialog/sub-device-dialog.vue'
import SubDriverInfoDetail from './sub-driver-info-detail.vue'
import PointTable from '../list-components/plc-dialog/point-table.vue'
import NetworkDialog from '../list-components/network-dialog/index.vue'
import {
  deleteBoxDriver,
  getBindDriverList,
  getBoxDriverList,
  getBoxDriverParams, getUserByDeviceId
} from '../../../../boot/miot/plc-list'
import { controllerType } from '../list-components/gateway-dialog/constant'
import { partcountObj } from '../list-components/plc-dialog/constant'

export default {
  name: 'driver-info-v2',
  components: { ControllerDialog, Unfold, DriverDialog, PointDialog, SubDeviceDialog, SubDriverInfoDetail, PointTable, NetworkDialog },
  props: {
    detailDriverParams: {
      type: Object,
      default: () => {}
    },
    detailInfo: {
      type: Object,
      default: () => {}
    },
    productsCnc: {
      type: Array,
      default: () => []
    },
    isPreVersion: {
      type: Boolean,
      default: false
    },
    updateVersion: {
      type: [String, Number],
      default: ''
    },
    boxRemark: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      thumbStyle: this.CommonConfig.thumbStyle, // 滚动条样式
      selectedTypeId: '',
      tab: 'driver',
      plcDriverInfo: {},
      driverParams: {
        ucloudBoxNum: '',
        gatewayId: '',
        productId: '',
        productName: '',
        gatewaySN: '',
        boxNum: '',
        driverId: '',
        subDeviceId: ''
      },
      driverConfigData: {},
      controllerType: '',
      driverList: [],
      driverDescInfo: {},
      driverInfo: {},
      typeList: [], // 驱动类型List
      dialogType: 1 // 弹框类型, 1新增2编辑
    }
  },
  computed: {
    // 过滤掉已经选择的驱动
    driverListFilter () {
      return this.driverList.filter(all => this.typeList.findIndex(select => all.value === select.driverId) === -1)
    },
    // 当前选择的驱动列表，用于编辑回显
    currentDriverData () {
      return this.driverList.find(item => item.value === this.currentDriverInfo.driverId)
    },
    // 当前选中的驱动
    currentDriverInfo () {
      return this.typeList.find(item => item.id === this.selectedTypeId) || {}
    },
    // 根据选择的driver获取详情
    driverDetail () {
      if (this.typeList.length > 0) {
        return this.currentDriverInfo?.driverName?.split('_') || []
      }
      return []
    },
    // 驱动描述
    driverDescription () {
      const driverId = this.currentDriverInfo?.driverId
      if (driverId) {
        return this.driverDescInfo[driverId] || '--'
      }
      return '--'
    },
    isCnc () {
      return this.controllerType === '0'
    },
    driverDevice () {
      const deviceList = this.driverInfo?.deviceListResVos
      if (deviceList) {
        const device = deviceList[0]
        return `${device.name}(${device.assetNumber})`
      }
      return '--'
    },
    driverDeviceObj () {
      const deviceList = this.driverInfo?.deviceListResVos
      if (deviceList) {
        const device = deviceList[0]
        return {
          label: `${device.name}(${device.assetNumber})`,
          value: device.assetNumber,
          id: device.id,
          partcountType: device.partcountType,
          partcountName: device.partcountType ? partcountObj[device.partcountType] : '清零'
        }
      }
      return {}
    },
    // 当为上个版本时候，驱动配置只允许一个
    disableAdd () {
      return this.isPreVersion && this.typeList.length > 0
    },
    controllerTypes () {
      controllerType[2].disabled = !!this.isPreVersion
      return controllerType
    }
  },
  watch: {
    detailDriverParams: {
      deep: true,
      immediate: true,
      handler (val) {
        if (val) {
          this.driverParams.ucloudBoxNum = val?.ucloudBoxNum ? val.ucloudBoxNum : ''
          this.driverParams.gatewayId = val?.gatewayId ? val.gatewayId : ''
          this.driverParams.productId = val?.productId ? val.productId : ''
          this.driverParams.productName = val?.productName ? val.productName : ''
          this.driverParams.gatewaySN = val?.gatewaySN ? val.gatewaySN : ''
          this.driverParams.productSN = val?.productSN ? val.productSN : ''
          this.driverParams.boxNum = val?.boxNum ? val.boxNum : ''
          this.driverParams.subDeviceId = val?.subDeviceId ? val.subDeviceId : ''
          this.driverConfigData.driverName = val?.driverName ? val.driverName : ''
          if (this.driverParams.gatewayId && this.driverParams.productId) {
            this.getDriverList()
          }
        }
      }
    },
    selectedTypeId: {
      immediate: true,
      handler (val) {
        if (val) {
          this.getDriverInfo()
        }
      }
    },
    typeList: {
      immediate: true,
      deep: true,
      handler (val) {
        this.$emit('changeDriverList', val)
      }
    },
    controllerType: {
      immediate: true,
      handler (val) {
        this.$emit('changeControllerType', val)
      }
    }
  },
  methods: {
    // 初始化
    init () {
      this.selectedTypeId = ''
      this.typeList = []
    },
    // 点击驱动列表
    onTypeClick (item) {
      this.selectedTypeId = item.id
      this.controllerType = item.type + ''
      if (this.isCnc) {
        this.tab = 'driver'
      }
    },
    // 获取已经绑定的驱动列表
    getType (ucloudBoxNum, updateVersion) {
      this.selectedTypeId = ''
      this.typeList = []
      getBoxDriverList(ucloudBoxNum, updateVersion).then(res => {
        this.typeList = res.data || []
        if (this.typeList.length > 0 && !this.selectedTypeId) {
          this.selectedTypeId = this.typeList[0]?.id
          this.controllerType = this.typeList[0]?.type + ''
        } else if (this.typeList?.length === 0) {
          this.selectedTypeId = ''
          this.controllerType = ''
        }
      })
    },
    // 获取驱动列表
    getDriverList () {
      const params = {
        gatewayId: this.driverParams.gatewayId,
        productId: this.driverParams.productId
      }
      if (!params.gatewayId || !params.productId) return
      getBindDriverList(params).then(res => {
        const resData = res.data
        if (resData) {
          this.driverList = resData.map(item => {
            this.driverDescInfo[item.driverID] = item?.description || '--'
            return {
              label: item.driverName,
              value: item.driverID,
              description: item.description,
              versionList: item.versionList || []
            }
          })
        }
      })
    },
    // 添加驱动
    addType () {
      this.dialogType = 1
      this.$refs.controllerDialog.showDialog()
    },
    // 选择类型
    changeType (val) {
      this.controllerType = val
      this.$nextTick(() => {
        this.configDialog = false
        this.$refs.driverDialog.showDialog()
      })
    },
    // 删除这个驱动
    delType () {
      this.$q.dialog({
        title: `<p class="dialog-notice-title">
<i class="iconfont icontubiao-28" ></i> 确定要删除该驱动吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        const params = {
          'driverName': this.currentDriverInfo.driverName,
          'driverId': this.currentDriverInfo.driverId,
          'subDeviceSn': this.currentDriverInfo.subDeviceSn,
          'type': this.currentDriverInfo.type,
          'boxId': this.driverParams.boxNum,
          'ucloudBoxId': this.driverParams.ucloudBoxNum,
          'productSN': this.driverParams.productSN,
          'deviceSN': this.driverParams.gatewaySN,
          'productId': this.driverParams.productId,
          'gatewayId': this.driverParams.gatewayId,
          'deviceDriverId': this.currentDriverInfo.id
        }

        deleteBoxDriver(params).then(res => {
          this.selectedTypeId = ''
          this.getType(this.detailDriverParams.ucloudBoxNum, this.updateVersion)
          this.$message.success('删除驱动成功')
        })
      })
    },
    // 驱动绑定成功
    successDriver (data) {
      this.selectedTypeId = data.boxDriverId
      Object.assign(this.driverConfigData, data)
      if (this.isCnc) {
        this.tab = 'driver'
      }
      // 绑定成功后,拉取最新的绑定驱动,然后再打开子设备配置
      getBoxDriverList(this.driverParams.ucloudBoxNum, this.updateVersion).then(res => {
        this.typeList = res.data || []
        // 如果是上个版本, 直接取第一个id
        if (this.isPreVersion && this.typeList.length > 0) {
          this.selectedTypeId = this.typeList[0].id
        }
        this.getDriverInfo().then(() => {
          this.$refs.driverDialog.hideDialog()
          this.$refs.subDeviceDialog.showDialog(this.driverInfo)
        })
      })
    },
    // 子设备配置成功
    successSubDevice () {
      this.getDriverInfo()
      this.$refs.subDeviceDialog.hideDialog()
      // 如果是新增的驱动,走点位配置
      if (this.dialogType === 1 && !this.isCnc) {
        this.$refs.pointDialog.showDialog()
      }
    },
    // 点位配置成功
    successPoint () {
      this.$refs.pointDialog.hideDialog()
      this.$refs.pointTable.getPointData()
    },
    // 驱动配置
    driverSetting () {
      this.dialogType = 2
      this.controllerType = this.currentDriverInfo.type + ''
      if (this.tab === 'driver') {
        this.$refs.driverDialog.showDialog(this.currentDriverInfo, this.currentDriverData, this.driverDeviceObj.value, this.driverDeviceObj.partcountType)
      } else if (this.tab === 'point') {
        this.$refs.pointDialog.showDialog()
      }
    },
    networkAsset () {
      this.$refs.networkDialog.showDialog()
    },
    // 网关驱动配置查询
    getDriverInfo () {
      return new Promise(resolve => {
        const driverId = this.currentDriverInfo.driverId
        if (!driverId) {
          resolve()
          return
        }
        const data = {
          boxId: this.driverParams.ucloudBoxNum,
          driverId,
          gateWayType: this.controllerType,
          updateVersion: this.updateVersion
        }
        if (this.isPreVersion && this.isCnc) {
          data.hwBoxId = this.detailDriverParams.boxNum
        }
        getBoxDriverParams(data).then(res => {
          const data = res.data
          this.driverInfo = data || {}
          if (this.isPreVersion) {
            if (this.isCnc) {
              this.driverInfo.collectType = this.driverInfo.serialPort ? '2' : '1'
            } else {
              this.driverInfo.collectType = '1'
            }
          }
          resolve()
        })
      })
    },
    toDetail () {
      const deviceId = this.driverDeviceObj?.id
      if (!deviceId) return
      this.$q.loading.show()
      getUserByDeviceId(deviceId).then(res => {
        const row = res.data
        this.$router.push({
          path: '/main/status-monitor-v3/machine-list/machine-detail',
          query: {
            boxUcloudNum: this.driverParams.ucloudBoxNum,
            id: deviceId,
            operatorName: row.operatorName,
            technicianName: row.technicianName,
            boxId: this.driverParams.boxNum,
            boxStrId: this.driverParams.boxNum,
            fromList: true,
            isPlc: 0
          }
        })
      }).finally(() => {
        this.$q.loading.hide()
      })
    }
  }
}
</script>

<style scoped lang="scss">
.icon-btn {
  width: 18px;
  height: 18px;
  min-width: 18px;
  min-height: 18px;
  padding: 0;
}

/deep/ .icon-btn .q-icon {
  font-size: 16px
}

/deep/ .left-part,
/deep/ .right-part {
  margin: 20px 0 20px 20px;
  box-shadow: 0px 0px 7px 0px rgba(22, 22, 22, 0.2);
  height: calc(100% - 40px) !important;
  width: 100% !important;
  flex: 1!important;
}

/deep/ .right-part {
  margin: 20px 20px 20px 0;
}

.left, .right {
  box-shadow: 0px 0px 7px 0px rgba(22, 22, 22, 0.2);
  border-radius: 6px;
  //padding: 20px 0;
}

.box {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-width: 300px;
  border-radius: 6px;
  overflow-y: hidden;
  overflow-x: auto;
  height: 100%;

  .box-header {
    flex: 40px 0;
    padding: 0 20px;
    line-height: 40px;
    font-size: 14px;

    .head-title {
      font-weight: bold;

      .iconfont {
        font-size: 14px !important;
      }
    }
  }

  &.left {
    .box-content {
      flex: 1;
      padding-bottom: 20px;

      .role-item {

        &.activated {
          background: #cfd6fe;
          color: $primary;
        }

        &:hover {
          background: #e8ebff;

          /deep/ .q-focus-helper {
            display: none;
          }
        }
      }

      .q-separator {
        margin-left: 20px;
        width: calc(100% - 40px);
      }
    }
  }
}

.status {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: $positive;
  margin-right: 8px;
}

.offline {
  background: $negative;
}

.relative {
  position: relative;
  margin: 12px;

  .btn-pos {
    position: absolute;
    right: 0px;
    top: 0px;
  }
}

.driver-box {
  margin: 20px;
  flex: 1;
}

.title {
  line-height: 1;
  font-size: 16px;
  font-weight: 500;
  color: #5f77fd;
}

.content-wrapper{
  padding: 20px;
  height: 540px;
  overflow-y: auto;
  box-shadow: 0px 0px 7px 0px rgba(22, 22, 22, 0.2);
  border-radius: 6px;
}

.margin-t-10{
  margin-top: 10px;
}

.margin-l-5{
  margin-left: 5px;
}
</style>
